import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import prismaClient from '@/config/prismaClient';
import { throwHttpException1 } from '@/utils/nesjUtils';

@Injectable()
export class CheckParamIsEmptyMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    // 1、校验整体参数是否传递
    if (Object.keys(req.body).length == 0) {
      throwHttpException1({
        state: '0',
        msg: '请检查参数是否正确！',
        data: '',
      });
    }
    // 2、校验必填参数是否传递
    const requiredFields = [
      { name: '用户名', field: 'Name' },
      { name: '手机号', field: 'Phone' },
      { name: '邮箱', field: 'Email' },
      { name: '密码', field: 'Password' },
      { name: '省份', field: 'ProvienceCode' },
      { name: '地市', field: 'CityCode' },
      { name: '区县', field: 'CountyCode' },
    ];
    const errFields = requiredFields.filter((f) => {
      if (!!!req.body[f.field]) {
        return f;
      }
    });
    console.log('errFields', errFields);

    if (errFields.length != 0) {
      throwHttpException1({
        state: '0',
        msg: `请检查参数是否正确！必填项: ${errFields.map((f) => f.name).join('、')}`,
        data: '',
      });
    }

    next();
  }
}

@Injectable()
export class CheckPhoneIsExistsMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    // console.log('路由拦截器嘿嘿嘿，我是局部中间件2');

    const baseUserList = await prismaClient.base_user.findMany({
      where: {
        Phone: req.body.Phone,
        IsDel: '0',
      },
    });
    if (baseUserList.length != 0) {
      throwHttpException1({
        state: '0',
        msg: '请检查参数是否正确！手机号已存在',
        data: '',
      });
    }
    // return res.status(200).json({ success: false, message: 'Invalid data' });

    // throw new HttpException(
    //   {
    //     data: '错误',
    //     resCode: '0',
    //   },
    //   HttpStatus.OK,
    // );
    // throwHttpException({
    //   errcode: ErrCode.ParamsError,
    //   errmsg: '参数错误2332',
    //   errstack: '',
    // });
    // console.log('下面代码继续');

    // res.send('拦截你');
    next();
  }
}
